#pragma once
#include<iostream>
#include<string>
#include<unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include"../CommonComponent/Log.hpp"
#include"common.hpp"

namespace ns_compile
{
    //编译时需要文件的整个路径，但不需要后缀
    class compile
    {
    public:
        compile()
        {}

        ~compile()
        {}

        static int Compile(std::string& filename)
        {
            int pid=fork();
            if(pid<0){
                Log(FATAL,"fork error\n");
                return -1;
            }
            else if(0==pid){
                //子进程
                std::string fileStderror=ns_common::fileUtility::AddCompileErrSuffix(filename).c_str();
                int fd=open(fileStderror.c_str(),O_WRONLY);
                if(fd<0)
                {
                    Log(ERROR,"can not open file\n");
                    exit(-1);
                }
                dup2(fd,2);
                execlp("g++","g++" ,ns_common::fileUtility::AddSrcSuffix(filename).c_str(),"-o",ns_common::fileUtility::AddExeSuffix(filename).c_str(),NULL);

                //执行到这里说明程序替换出错
                Log(ERROR,"execlp error\n");
                exit(-1);
            }
            else{
                //父进程
                int status=0;
                waitpid(pid,&status,0);
                std::string fileExe=ns_common::fileUtility::AddExeSuffix(filename);
                if(ns_common::fileUtility::IsFileEsist(fileExe)){
                    //编译成功
                    Log(INFO,"compile successfully\n");
                    return 0;
                }
                
                if(ns_common::fileUtility::IsFileEmpty(ns_common::fileUtility::AddCompileErrSuffix(filename))){
                    //发生了内部错误导致子进程exit()退出
                    return -1;
                }

                Log(INFO,"compile error\n");
                return 1;
            } 
        }
    };
}